import os
from google.appengine.ext.webapp import template

from google.appengine.ext import webapp

from models.Authentication import *
import Cookie
import uuid

class Login(webapp.RequestHandler):
  
  def get(self, flash=None):
    """Responds to get requests to the controller"""
    template_values = {"flash":flash}
    path= os.path.join(os.path.dirname(__file__), "../templates/login.html")
    self.response.out.write(template.render(path, template_values))
    
  def post(self):
    """This will do the login authentication and set the user session"""
    attempted_user = self.request.get("user")
    attempted_password = self.request.get("password")
    
    res = authenticate(email=attempted_user, password=attempted_password)
    
    if res:
      session = self.create_session(user=res)
      self.response.headers.add_header('Set-Cookie', session.output("header="))
      return self.redirect("/group")
      
    else:
      logging.info("I got here")
      flash = "Your Username or Password was incorrect please try again"
      self.get(flash=flash)
     
    
  def create_session(self, user=None):
    """This is a priavte implementation method that is used to create the  
    actual session object that we will return to the user"""
    cookie = Cookie.SimpleCookie()
    cookie["user_id"] = user.key().id()
    cookie["session_id"] = str(uuid.uuid4())
    
    return cookie
    
    
class Logout(webapp.RequestHandler):
  """This class will handle the logout which will set the cookie to 
  invalid and then redirect to login page"""

  def get(self):
    """Will handle get request"""
    # create the new invalid cookie
    cookie = Cookie.SimpleCookie()
    cookie["user_id"] = 0
    cookie["session_id"] = -1
    # set the cookie in http header
    self.response.headers.add_header('Set-Cookie', cookie.output("header="))
    
    # redirect to login page
    return self.redirect("/login")